package com.jihox.abookpro;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jihox.abookpro.R;
import com.jihox.abookpro.domain.BookProject;
import com.jihox.abookpro.domain.Caption;

public class ChangeCaptionActivity extends BaseActivity{

	private int currentIndex = 0;
	private int pageNum = 0;
	private int captionNum = 0;
	private EditText captionContentView = null;
	private Button saveButton = null;
	private BookProject bookProject = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_change_caption);
		getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		getWindow().setGravity(Gravity.BOTTOM);
		captionContentView = (EditText)findViewById(R.id.caption_content);
		saveButton = (Button) findViewById(R.id.btnSave);
		Bundle bundle = this.getIntent().getExtras();
		currentIndex = bundle.getInt("CurrentIndex");
		pageNum = bundle.getInt("PageNum"); 
		captionNum = bundle.getInt("CaptionNum");
		MyApplication application = MyApplication.getInstance();
		bookProject = application.getBookProject();
		
		Caption caption = bookProject.getBook().getPages().get(pageNum)
				.getCaptions().get(captionNum);
		if (caption != null) {
			String text = caption.getText();
			
			if (caption.isShowTempText()){
				text = caption.getTempText();
			}
			if (text == null) {
				text = "";
			}
			captionContentView.setText(text);
			captionContentView.setSelection(text.length());
		}
		
		saveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ChangeCaptionActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
				if (captionNum == 0
						&& "".equals(captionContentView.getText().toString()
								.trim()) && pageNum==0) {
					showDialog();
				} else {
					
					bookProject.getBook().getPages().get(pageNum).getCaptions()
					.get(captionNum).setTempText(captionContentView.getText().toString());
					bookProject.getBook().getPages().get(pageNum).setNeedRedraw(true);
					bookProject.getBook().getPages().get(pageNum).getCaptions()
					.get(captionNum).setShowTempText(true);
					backMethod(1);
				}
			}
		});
		
		float screenRatio = 1f;
		if (captionNum == 0){
			screenRatio =CurlActivity.coverPageScreenAndRealRatio*0.9f;
		}else{
			screenRatio =CurlActivity.innerPageScreenAndRealRatio*0.9f;
		}
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paint.setAntiAlias(true);
		paint.setStrokeWidth(3);
		paint.setTextSize((float) (caption.getFont().getSize()* screenRatio/ 2.85));
				
		Typeface typeface;
		if (caption.getFont().getName().startsWith("fonts/")) {
			try {
				typeface = Typeface.createFromAsset(
						this.getAssets(), caption
								.getFont().getName());
			} catch (Exception ex) {
				typeface = Typeface.create(caption.getFont()
						.getName(), caption.getFont()
						.getStyle());
			}
		} else {
			typeface = Typeface.create(caption.getFont()
					.getName(), caption.getFont().getStyle());
		}
		paint.setTypeface(typeface);// 设置字体类型
		
		captionContentView.addTextChangedListener(new TextFilter(paint, caption.getWidth()*screenRatio,captionContentView));
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				showInputMethod();
			}
		}, 500);
	}

	class TextFilter implements TextWatcher {
		private Paint mPaint;
		private float mCaptionWidth;
		private EditText mEdit;
		private String beforeText;
		
		public TextFilter(Paint paint,float captionWidth,EditText edit) {  
			mPaint = paint;
			mCaptionWidth = captionWidth;
			mEdit = edit;
        }  
		
		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void beforeTextChanged(CharSequence str, int start, int count, int after) {
			 beforeText = str.toString();//这里用s.toString()而不直接用s是因为如果用s，那么，tmp和s在内存中指向的是同一个地址，s改变了，tmp也就改变了，那么表情过滤就失败了
		}

		@Override
		public void onTextChanged(CharSequence str, int start, int before, int count) {

			if(count >= 2){//表情符号的字符长度最小为2
			    int len = str.length();
			    for (int i=0;i < len; i++){
			    	char codePoint = str.charAt(i);
			    	if(isEmojiCharacter(codePoint)){
				    	//是表情符号就将文本还原为输入表情符号之前的内容
				    	mEdit.setText(beforeText);
				    	mEdit.invalidate();
				    	Toast.makeText(ChangeCaptionActivity.this,
				        "不支持表情输入", Toast.LENGTH_SHORT).show();
				    	mEdit.setSelection(mEdit.getText().length());
				    	return;
				    }
			    }
			}
		
			float textWidth = 0;
			if (str != null && str.length() > 0) {
				textWidth = mPaint.measureText(str.toString());
				
				if (textWidth>mCaptionWidth){
					mEdit.setText(beforeText);
			    	mEdit.invalidate();
					Toast.makeText(ChangeCaptionActivity.this, R.string.T_Caption_Reached_Maximun, Toast.LENGTH_SHORT).show();
					mEdit.setSelection(mEdit.getText().length());
				}
			}
		    
		}  
		
	}
	
    private static boolean isEmojiCharacter(char codePoint) {
        return !((codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
    }
	
	private void showInputMethod() {
		captionContentView.setFocusable(true);
		captionContentView.setFocusableInTouchMode(true);
		captionContentView.requestFocus();
		InputMethodManager inputManager = (InputMethodManager) captionContentView
				.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		inputManager.showSoftInput(captionContentView, WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		 
	}

	private void showDialog() {

		final Dialog dialog = new Dialog(ChangeCaptionActivity.this,
				R.style.JHDialog);
		// 设置它的ContentView
		dialog.setContentView(R.layout.dialog_general);
		Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
		Button buttonCancel = (Button) dialog
				.findViewById(R.id.dialog_button_cancel);
		TextView dialogTitle = (TextView) dialog
				.findViewById(R.id.dialog_title);
		TextView dialogMessage = (TextView) dialog
				.findViewById(R.id.dialog_message);

		buttonOK.setBackgroundResource(R.drawable.green_style);
		buttonCancel.setBackgroundResource(R.drawable.grey_style);
		buttonOK.setText(R.string.T_Ok);

		dialogTitle.setText(R.string.T_Kindly_Reminder);
		dialogMessage.setText(R.string.T_Need_Title);

		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT); // , 1是可选写的
		lp.setMargins(0, 0, 0, 0);

		buttonOK.setLayoutParams(lp);
		buttonCancel.setVisibility(View.GONE);

		buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				Timer timer = new Timer();
				timer.schedule(new TimerTask() {
					public void run() {
						showInputMethod();
					}
				}, 500);
			}
		});
		dialog.show();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		backMethod(0);
	}

	private void backMethod(int resultCode) {
		Intent intent = new Intent();
		intent.setClass(ChangeCaptionActivity.this, CurlActivity.class);
		Bundle mBundle = new Bundle();
		mBundle.putInt("CurrentIndex", currentIndex);
		intent.putExtras(mBundle);
		ChangeCaptionActivity.this.setResult(resultCode, intent);
		this.finish();
	}
}
